package com.hpp.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.hpp.model.Attachment;
import com.hpp.service.IManageService;
import com.hpp.utils.ConfigUtil;
import com.hpp.utils.DateUtils;
import com.hpp.utils.ImageHelper;
import com.hpp.utils.RespJson;
import com.hpp.utils.ResultCode;
import com.hpp.utils.UploadFileUtils;
import com.hpp.utils.UploadState;

@Controller
@RequestMapping(value = "/manage")
public class ManageController {
	
	@Autowired
	IManageService manageService;
	
	/**
	 * @Title uploadFile  
	 * @Description 上传图片
	 * @author hanpp
	 * @param request
	 * @param session
	 * @return RespJson
	 * @date 2019年1月15日 下午7:52:32  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/file/upload")
	public String uploadFile(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		if (file == null) {
			file = multipartRequest.getFile("file1");
		}
		String name = file.getOriginalFilename();
		//缩略图测试
		HashMap<String, Object> result = uploadFileTypeThumb(file, name);
		if ("true".equals(result.get("isTrue").toString())) {
			result.put("imgUrl", ConfigUtil.get("url")
					+ result.get("imgUrl").toString());
			return JSON.toJSONString(new RespJson(true, "文件上传成功", ResultCode.SUCCESS, result));
		} else {
			return JSON.toJSONString(new RespJson(true, "文件上传失败", ResultCode.SUCCESS, result));
		}
	}

	public HashMap<String, Object> uploadFileType(MultipartFile file,
			String FileName) {
		HashMap<String, Object> result = new HashMap<>();
		int end = FileName.lastIndexOf(".");
		String fn = FileName.substring(end);
		String name = DateUtils.formatDate(new Date(),
				DateUtils.yyyyMMddHHmmss) + fn;
		InputStream is = null;
		if (file != null) {
			// name = file.getOriginalFilename();
			try {
				is = file.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String path = getFilePath();
		String filepath = ConfigUtil.get("upload.path")+path;
		UploadState record = null;
		try {
			Attachment attachment = new Attachment();
			attachment.setFileName(file.getName());
			attachment.setFilePath(path+"/"+name);
			attachment.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.simple));
			manageService.addAttachment(attachment);
			record = UploadFileUtils.upload4Stream(name, filepath, is);
			result.put("isTrue", "true");
			result.put("imgUrl", path+"/"+name);
			result.put("imgId", attachment.getId());
			result.put("path", path+"/"+name);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("isTrue", "false");
		}
		return result;
	}
	
	/**
	 * @Title uploadFileTypeThumb  
	 * @Description 缩略图处理
	 * @author 韩鹏鹏
	 * @param file
	 * @param FileName
	 * @return HashMap<String,Object>
	 * @date 2018年5月3日 下午5:48:50  
	 * @throws
	 */
	public HashMap<String, Object> uploadFileTypeThumb(MultipartFile file,
			String fileName) {
		HashMap<String, Object> result = new HashMap<>();
		int end = fileName.lastIndexOf(".");
		String fn = fileName.substring(end);
		String name = DateUtils.formatDate(new Date(),
				DateUtils.yyyyMMddHHmmss) + fn;
		InputStream is = null;
		if (file != null) {
			// name = file.getOriginalFilename();
			try {
				is = file.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String path = getFilePath();
		String filepath = ConfigUtil.get("upload.path")+path;
		try {
			boolean flag = false;
			Attachment attachment = new Attachment();
			//大于1M做缩略处理
			attachment.setFileName(name);
			if (file.getSize() > 1048576) {
				attachment.setFilePath(path+"/"+name);
				flag = true;
			}else {
				attachment.setFilePath(path+"/"+name);
			}
			attachment.setCreateTime(DateUtils.formatDate(new Date(),
					DateUtils.simple));
			manageService.addAttachment(attachment);
			UploadState record = UploadFileUtils.upload4Stream(name, filepath, is);
			if (flag) {
				//生成等比缩略图
				ImageHelper.scaleImage(filepath + "/" + name, filepath + "/" + name, 0.6);
				//生成自定义缩略图
				//ImageUtil.thumbnailImage(filepath + "\\" + name, 800, 500, ImageUtil.DEFAULT_PREVFIX,ImageUtil.DEFAULT_FORCE);
				result.put("imgUrl", path+"/"+name);
				result.put("path", path+"/"+name);
			}else {
				result.put("imgUrl", path+"/"+name);
				result.put("path", path+"/"+name);
			}
			result.put("isTrue", "true");
			result.put("imgId", attachment.getId());
			result.put("fileName", name);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("isTrue", "false");
		}
		return result;
	}
	
	/**
	 * @Title uploadAttachment  
	 * @Description 上传附件
	 * @author hanpp
	 * @param request
	 * @param session
	 * @return RespJson
	 * @date 2019年1月15日 下午7:52:20  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/attachment/upload")
	public RespJson uploadAttachment(HttpServletRequest request, HttpSession session) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		if (file == null) {
			file = multipartRequest.getFile("file1");
		}
		String name = file.getOriginalFilename();
		int index = name.lastIndexOf(".");
		String fileName = name.substring(index + 1, name.length());
		//HashMap<String, Object> result = uploadFileType(file, name);
		//缩略图测试
		HashMap<String, Object> result = uploadFileType(file, name);
		if ("true".equals(result.get("isTrue").toString())) {
			result.put("fileUrl", ConfigUtil.get("url")
					+ result.get("imgUrl").toString());
			return new RespJson(true, "", ResultCode.SUCCESS, result);
		}
		return new RespJson(false, "文件上传失败", ResultCode.ERROR, null);

	}

	private  String getFilePath() {
		long time = System.currentTimeMillis();
		String value = String.valueOf(time);
		String sub = value.substring(value.length()-4);
		String s1 = sub.substring(0,2);
		String s2 = sub.substring(2);
		return s1+"/"+s2;
	}
}
